class Drag extends Event {
  constructor(el) {
    super();
    this.el = el;
    this.startMouse = {}; // 按下时，鼠标坐标
    let move = (e) => {
      this.move(e);
    };
    this.el.addEventListener("mousedown", (e) => {
      this.start(e);
      document.addEventListener("mousemove", move);
      document.addEventListener(
        "mouseup",
        () => {
          this.end(e);
          document.removeEventListener("mousemove", move);
        },
        { once: true }
      );
    });
  }
  start(e) {
    /*
     * 拖拽：获取按下时元素坐标
     * 框选：创建元素用于画框
     */
    this.startMouse = {
      x: e.clientX,
      y: e.clientY,
    };
    this.dispatch("dragstart", e);
  }
  move(e) {
    /*
     * 拖拽：用按下时元素坐标+差值，计算当前元素的坐标
     * 框选：计算框的宽、高、left、top
     */
    let nowMouse = {
      x: e.clientX,
      y: e.clientY,
    };
    let dis = {
      x: nowMouse.x - this.startMouse.x,
      y: nowMouse.y - this.startMouse.y,
    };
    this.dispatch("dragmove", e, dis, nowMouse);
  }
  end(e) {
    /*
     * 拖拽：不作处理
     * 框选：移除框
     */
    this.dispatch("dragend", e);
  }
}